
package com.common.myspring.core.proxy;

import com.common.myspring.annotation.LogAnnotation;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @title: JdkProxy
 * @Author xu-xiang
 * @Date: 2023/8/30 16:57
 * @description:
 */
public class JdkProxy_bak<T> implements InvocationHandler {

    private final T bean;

    public JdkProxy_bak(T bean) {
        this.bean = bean;
    }

    @SuppressWarnings("unchecked")
    public T doProxy() {
        return (T) Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), this);
    }

    public static <T> T createProxyObject(T bean) {
        return new JdkProxy_bak<>(bean).doProxy();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Method realMethod = getRealMethod(bean, method);
        if (!realMethod.isAnnotationPresent(LogAnnotation.class)) {
            return method.invoke(bean, args);
        }

        System.out.println("JDK代理方法" + method.getName() + "执行开始!");
        Object proceed = method.invoke(bean, args);
        System.out.println("JDK代理方法" + method.getName() + "执行结束!\n");
        return proceed;
    }

    /**
     * 获取接口对应的实现类本身的实现方法
     */
    private Method getRealMethod(Object bean, Method interfaceMethod) {
        Method method = null;
        try {
            method = bean.getClass().getMethod(interfaceMethod.getName(), interfaceMethod.getParameterTypes());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return method;

    }
}
